#define _CRT_SECURE_NO_WARNINGS

#include"list.h"
LTNode* BuyListNode(LTDataType x) {
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL) {
		perror("malloc failed");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
}

LTNode* LTInit() {
	LTNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LTPrint(LTNode* phead) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur!=phead) {
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void LTPushBack(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* newnode = BuyListNode(x);
	LTNode* cur = phead;
	while (cur->next!=phead) {
		cur = cur->next;
	}
	cur->next = newnode;
	newnode->next = phead;
	newnode->prev = cur;
	phead->prev = newnode;
}

void LTPushFront(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* tmp = phead->next;
	LTNode* newnode = BuyListNode(x);
	phead->next = newnode;
	newnode->next = tmp;
	tmp->prev = newnode;
	newnode->prev = phead;
}

void LTPopBack(LTNode* phead) {
	assert(phead);
	assert(phead->next != phead);
	LTNode* tmp1 = phead->prev;
	LTNode* tmp2 = tmp1->prev;
	free(tmp1);
	tmp2->next = phead;
	phead->prev = tmp2;
}
void LTPopFront(LTNode* phead) {
	assert(phead);
	assert(phead->next != phead);
	LTNode* tmp = phead->next->next;
	free(phead->next);
	phead->next = tmp;
	tmp->prev = phead;
}


int LTSize(LTNode* phead) {
	assert(phead);
	int count = 0;
	LTNode* cur = phead->next;
	while (cur != phead) {
		count++;
		cur = cur->next;
	}
	return count;
}

LTNode* LTFind(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x) {
	assert(pos);
	LTNode* newnode = BuyListNode(x);
	LTNode* tmp = pos->prev;
	tmp->next = newnode;
	newnode->prev = tmp;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos) {
	assert(pos);
	LTNode* tmp1 = pos->next;
	LTNode* tmp2 = pos->prev;
	free(pos);
	tmp1->prev = tmp2;
	tmp2->next = tmp1;
}

void LTDestroy(LTNode* phead) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead) {
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}